import {Component, Input, OnDestroy, OnInit, ViewChild, ViewEncapsulation} from '@angular/core';
import {ActivatedRoute, Params, Router} from "@angular/router";
import {OrderService} from "@order/order.service";
import {AuthService} from "@shared/service/auth/auth.service";
import {MineService} from "@mine/mine.service";

import {ToolsService} from "@shared/service/tools/tools.service";
import {GoodsService} from "@goods/goods.service";
import {SeedInfiniteScroll} from "@shared/components/infinite-scroll/seed-infinite-scroll/seed-infinite-scroll.component";
import {Subject} from "rxjs/Rx";
import {EventsService} from "@core/events/events.service";
import {CouponRespVO, GoodsSkuOrderVO, UserDeliveryAddressVO} from "@interface/index";
import {HaggleService} from "../../haggle/haggle.service";


@Component({
  selector: 'seed-confirm-order',
  templateUrl: 'confirm-order.component.html',
  styleUrls: ['confirm-order.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ConfirmOrderComponent implements OnInit, OnDestroy {
  @ViewChild(SeedInfiniteScroll) infiniteScroll;
  @Input() markType;

  public goodsQuantity = 0;
  public skuCode: string;
  private userId: string;
  public goodsCateCode1 = '';
  public goodsSkuDetail: GoodsSkuOrderVO;
  public ngUnsubscribe: Subject<void> = new Subject<void>();
  public usableCouponList: Array<CouponRespVO> = []; // 可用优惠券列表
  public defaultAddress: UserDeliveryAddressVO = new UserDeliveryAddressVO();
  public hasAddress = false; // 是否有地址
  public canClick = true; // 确认是否占击过
  public crowdCode: string;
  public couponCodeId: number; // 优惠券ID
  public totalPrice: number;  // 实际付款金额(减去优惠劵)
  public choose = false; // 是否已选择优惠劵
  public couponValue: number; // 优惠券金额
  public haggleAmount: number; // 砍价金额
  public params = { // 可用优惠券信息
    totalAmount: 0,
    page: 1,
    rows: 200,
  };
  public haggleInfo = { // 砍价ID 和 砍价发起人ID
    haggleId: 0,
    initiatorId: '',
  };
  public couponTotal: number;
  public cardChooseIndex: number;

  constructor(public orderService: OrderService,
              public authService: AuthService,
              private route: ActivatedRoute,
              public router: Router,
              public events: EventsService,
              public goodsService: GoodsService,
              public haggleService: HaggleService,
              public mineService: MineService,
              public toolsService: ToolsService) {
    this.route.queryParams
      .subscribe((param: Params) => {
        this.skuCode = param['skuCode'];
        this.goodsQuantity = param['quantity'];
        this.goodsCateCode1 = param['goodsCateCode'];
        this.haggleInfo.haggleId = param['haggleId'];
        this.haggleInfo.initiatorId = param['initiatorId'];
        if (param['crowdCode']) {
          this.crowdCode = param['crowdCode'];
        }
        this.userId = this.authService.getUserId();
        this.getAddrList();
        this.getGoodsSkuDetail();
        this.getHaggleDetail();
      });
  }


  /**
   * @author @chensk740
   * @date  2017.09.21
   * @description 获取地址信息列表
   * @constructor
   */
  getAddrList() {

    this.mineService.getUserAddress(this.authService.getUserId()).subscribe((res) => {
      if (res.result === '0') {
        if (res.data.list && res.data.list.length > 0) {
          this.hasAddress = true;
          const index = localStorage.getItem('addressIndex');
          if (index) {
            this.defaultAddress = res.data.list[index];
          } else {
            this.defaultAddress = res.data.list[0];
          }
        }
      }
    });
  }


  /**
   * @author @chensk740
   * @date  2017.09.21
   * @modify ouxh 2017.11.9   // 增加接口返回错误码提示
   * @description 下单(status=1:普通商品，直接去支付页，status=9：是赛事或票务，跳到分类接口，status=2：免费普通商品，直接跳到结果页，不用支付）
   * @constructor
   */
  postSubmitOrder() {
    if (this.canClick) {
      this.canClick = false;
    } else {
      return;
    }
    if (!this.defaultAddress.id && this.goodsCateCode1 !== 'V20') {
      this.toolsService.showToast('请选择收货地址！');
      return;
    }
    const data = {
      addressId: this.defaultAddress.id,
      couponCodeId: this.couponCodeId,
      haggleId: this.haggleInfo.haggleId,
      initiatorId: this.haggleInfo.initiatorId,
      "detailList[0].skuCode": this.skuCode,
      "detailList[0].quantity": this.goodsQuantity
    };
    this.toolsService.showLoading();
    this.orderService.postOrderInfo(data).subscribe((res) => {
      if (res.result === '0') {

        // 如果是V20众筹产品先进行众筹信息登记
        if (this.goodsCateCode1 === 'V20') {
          const paramData = {
            crowdCode: this.crowdCode,
            orderNumber: res.data.orderNumber,
            skuCode: this.skuCode
          };
          this.orderService.crowdSupport(paramData).subscribe((corowd_res) => {
            if (corowd_res.result !== '0') {
              this.toolsService.showToast(res.msg);
              return;
            } else {
              this.orderStatusGo(res);
            }
          });
        } else {
          // 非众筹产品
          this.orderStatusGo(res);
        }

      } else if (res.result === '21079') {   // 该错误码为下单时候人数不符， 平台接口增加了data里的字段，需要处理后再展示
        this.toolsService.hideLoading();
        this.toolsService.showToast(`购买数量 ${res.data.minTeamMember} ~ ${res.data.maxTeamMember}`);
      } else if (res.result === '13014') {
        // 砍价活动防止重复提交
        this.toolsService.showToast(res.msg);
      } else {
        this.toolsService.hideLoading();
        this.toolsService.showToast(res.msg);
      }
    });
  }


  /**
   * @author @chensk740
   * @date  2017.11.21
   * @description 下单
   * @description 根据订单类型走下一步
   * @param res：生成订单后返回数据，status：订单类型，
   * (status=1:普通商品，直接去支付页，
   * status=9：是赛事或票务，跳到分类接口，
   * status=2：免费普通商品，直接跳到结果页，不用支付）
   */
  orderStatusGo(res) {
    if (res.data.status === 1) {
      this.router.navigate(['/payment/'], {queryParams: {orderNumber: res.data.orderNumber}});
    } else if (res.data.status === 9) {
      const data = {
        goodsCode: '',
        goodsCateCode1: '',
        goodsCateCode: '',
        skuCode: this.skuCode,
        orderNumber: res.data.orderNumber
      };
      this.handleOtherGoods(data);
    } else if (res.data.status === 2) {
      // this.router.navigate(['/payment/result', res.data.orderNumber]);
      this.router.navigate(['/payment/result'], {queryParams: {mchOrderNumber: res.data.orderNumber}});
    }
  }

  /**
   * @author @chensk740
   * @date  2017.09.21
   * @description 下单
   * @description 如果下单结果返回为9调用商品模板信息接口
   * @param data
   */
  handleOtherGoods(data) {
    const query = Object.assign(this.haggleInfo, {
      skuCode: this.skuCode
    });
    this.orderService.getGoodsSkuDetail(query).subscribe((res) => {
      if (res.result === '0') {
        data.goodsCode = res.data.goodsCode;
        data.goodsCateCode = res.data.goodsCateCode;
        data.goodsCateCode1 = res.data.goodsCateCode1;
        this.getGoodsTemplateInfo(data);
      }
    });
  }


  /**
   * @author @chensk740
   * @date  2017.09.21
   * @modifier @zhupw1360
   * @date  2017.11.07
   * @description 下单
   * @description 获得商品模板信息接口url然后跳转
   * @param data
   */
  getGoodsTemplateInfo(data) {
    this.orderService.getGoodsTemplateUrl(data);
  }

  /**
   * @author @chensk740
   * @date  2017.09.21
   * @modify 2018-01-05 @zhupw1360 新增 totalPrice，totalAmount
   * @description 下单
   * @description 查询赛事信息
   * @param skuCode
   */
  getGoodsSkuDetail() {
    const query = Object.assign(this.haggleInfo, {
      skuCode: this.skuCode
    });
    if (query) {
      this.orderService.getGoodsSkuDetail(query)
        .subscribe((res) => {
          this.goodsSkuDetail = res.data;
          this.params.totalAmount = res.data.salePrice;
          this.totalPrice = res.data.salePrice * this.goodsQuantity;
          if (res.data.preferentialPrice) {
            this.totalPrice -= res.data.preferentialPrice;
          }
          this.getUsableCouponList();
        });
    }
  }


  /**
   * @author @chensk740
   * @date  2017.09.21
   * @description 下单
   * @description 跳转到地址列表
   * @param skuCode quantity goodsCateCode
   */
  goToAddressList() {
    this.router.navigate(['/mine/address/list'], {
      queryParams: {
        skuCode: this.skuCode,
        quantity: this.goodsQuantity,
        goodsCateCode: this.goodsCateCode1,
        haggleId: this.haggleInfo.haggleId,
        initiatorId: this.haggleInfo.initiatorId,
      }
    });
  }


  /**
   * @description 可用优惠券列表
   * @author @zhupw1360
   * @date 2018-01-02
   * @param param { totalAmount ， page , rows }
   */
  getUsableCouponList() {
    // console.log(this.params);
    this.goodsService.getUsableCouponList(this.params)
      .takeUntil(this.ngUnsubscribe).subscribe(res => {
      if (res.result === '0' && res.data && res.data.list.length > 0) {
        this.couponTotal = res.data.total;
        this.usableCouponList = [...this.usableCouponList, ...res.data.list];
      }
    });
  }

  /**
   * @description 选择优惠券
   * @author @zhupw1360
   * @date 2018-01-05
   * @param params { codeId ， couponValue , index }
   */
  chooseCoupon(codeId: number, couponValue: number, index: number) {
    this.totalPrice = this.goodsSkuDetail.salePrice * this.goodsQuantity;
    this.choose = true;
    this.couponCodeId = codeId;
    this.couponValue = couponValue;
    this.totalPrice -= couponValue;
    if (this.totalPrice < 0) {
      this.totalPrice = 0;
    }
    this.cardChooseIndex = index;
    this.events.publish('modal:close');
  }

  // 跳转优惠券说明
  goToCouponExplain() {
    this.router.navigate(['/goods/coupon/explain']);
  }

  // 获取活动优惠金额
  getHaggleDetail() {
    this.haggleService.getHaggleDetail(this.haggleInfo)
      .takeUntil(this.ngUnsubscribe)
      .subscribe(res => {
        if (res.result === '0' && res.data) {
          // this.totalPrice = this.goodsSkuDetail.salePrice * this.goodsQuantity;
          this.haggleAmount = res.data.haggleAmount;
          // this.totalPrice -= this.haggleAmount;
        }
      });
  }

  ngOnInit() {
  }

  ngOnDestroy() {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }

}
